package cn.anecansaitin.firecrafting.common.crafting;

import cn.anecansaitin.firecrafting.ModConstant;
import cn.anecansaitin.firecrafting.api.common.IResultType;
import cn.anecansaitin.firecrafting.api.common.block.entity.IFireInterfaceEntity;
import cn.anecansaitin.firecrafting.api.client.crafting.IJEIRecipeRender;
import cn.anecansaitin.firecrafting.client.crafting.FireFluidRecipeRender;
import cn.anecansaitin.firecrafting.common.Config;
import cn.anecansaitin.firecrafting.common.util.ModJsonReader;
import cn.anecansaitin.firecrafting.common.util.Directions;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistryEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

//生成流体的配方
public class FireFluidRecipe extends SimpleFireRecipe {
    private final FluidStack outputs;

    public FireFluidRecipe(ResourceLocation id, ImmutableList<Block> fireBlock, NonNullList<Ingredient> inputs, FluidStack outputs) {
        super(id, fireBlock, inputs);
        this.outputs = outputs;
    }

    @Override
    public IJEIRecipeRender getRender() {
        return FireFluidRecipeRender.INSTANCE;
    }

    //在配方正确时进行一系列行为
    @Override
    public boolean doAction(List<ItemStack> stacks, BlockPos pos, Level world) {
        //检测环境和配方
        if (match(stacks, pos, world)) {
            //记录剩余数量
            FluidStack remain = outputs.copy();
            //为火焰六个面的方块进行检测，每个面都尝试存入流体
            for (Direction direction : Directions.ALL_SIDE) {
                //获取方块实体
                BlockEntity entity = world.getBlockEntity(pos.relative(direction));
                //判断方块实体存在
                if (entity != null) {
                    //获取指定方向的能量能力（获取朝向火焰的那个面）
                    LazyOptional<IFluidHandler> cap = entity.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY);
                    //判断能力存在
                    if (cap.isPresent()) {
                        //获取能力对象
                        IFluidHandler fluid = cap.orElseThrow(RuntimeException::new);
                        //存入流体并减少剩余流体数量
                        fluid.fill(remain, IFluidHandler.FluidAction.EXECUTE);
                        //判断流体是否耗尽
                        if (remain.isEmpty()) {
                            break;
                        }
                    }
                }
            }

            //若流体数量大于1000则在世界上生成流体
            if (!remain.isEmpty() && remain.getAmount() >= 1000) {
                world.setBlockAndUpdate(pos, ForgeRegistries.BLOCKS.getValue(remain.getFluid().getRegistryName()).defaultBlockState());
            }
            return true;
        }
        return false;
    }

    @Override
    public int doAction(IFireInterfaceEntity fireInterface) {
        //获取该接口能处理的类型
        List<IResultType> types = fireInterface.actionType();
        //判断接口支持的类型
        if (types.stream().anyMatch(IResultType.FLUID::equals)) {
            //检测配方
            if (!match(fireInterface.getMaterial(), fireInterface.getFire())) {
                return -1;
            }
            //获取流体能力
            LazyOptional<IFluidHandler> energyHandler = fireInterface.getCapForOutput(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY);
            //如果不能力存在
            if (!energyHandler.isPresent()) {
                return -1;
            }
            //获取流体对象
            IFluidHandler fluid = energyHandler.orElseThrow(() -> new RuntimeException("不可能触发的异常"));
            //尝试存入
            int i = fluid.fill(outputs, IFluidHandler.FluidAction.SIMULATE);
            //检测可存入能量是否等于总输出
            if (i != outputs.getAmount()) {
                return 0;
            }
            //正真存入
            fluid.fill(outputs.copy(), IFluidHandler.FluidAction.EXECUTE);
            return 1;
        }

        return -1;
    }

    public FluidStack getOutputs() {
        return outputs;
    }

    //返回配方指定的序列化器
    @Override
    public @NotNull RecipeSerializer<?> getSerializer() {
        return ModRecipeTypes.FIRE_FLUID_SERIALIZER.get();
    }

    //序列化器实现类
    public static class Serializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<FireFluidRecipe> {
        public static final String NAME = ModConstant.MOD_ID + ":fire_fluid_crafting";

        //从json入去配方
        @Override
        public @NotNull FireFluidRecipe fromJson(@NotNull ResourceLocation id, @NotNull JsonObject json) {
            //获取配方物品成分
            NonNullList<Ingredient> nonnulllist = ModJsonReader.ingredientsFromJson(GsonHelper.getAsJsonArray(json, "ingredients"));
            //判断配方成分的可用性
            if (nonnulllist.isEmpty()) {
                throw new JsonParseException("火焰燃烧(流体)配方内没有任何原料 No ingredients for fire fluid recipe");
            } else if (nonnulllist.size() > Config.WORLD_MAX_COUNT.get()) {
                throw new JsonParseException("火焰燃烧(流体)配方内的原料超出上限" + Config.WORLD_MAX_COUNT.get() + "  Too many ingredients for fire fluid recipe. The maximum is " + Config.WORLD_MAX_COUNT.get());
            }
            //获取配方流体产物
            FluidStack fluid = ModJsonReader.fluidFromJson(json, "output");
            //判断产物可用性
            if (fluid.isEmpty()) {
                throw new JsonParseException("火焰燃烧(流体)配方内没有任何原料 No ingredients for fire fluid recipe");
            }
            //获取可用火焰
            ImmutableList<Block> fire = ImmutableList.copyOf(ModJsonReader.blocksFromJson(json, "fire"));
            //判断火焰可用性
            if (fire.isEmpty()) {
                throw new JsonParseException("火焰燃烧(流体)配方内没有指定火焰 No fire block for fire fluid recipe");
            }
            return new FireFluidRecipe(id, fire, nonnulllist, fluid);
        }

        //从网络读取配方
        @Nullable
        @Override
        public FireFluidRecipe fromNetwork(@NotNull ResourceLocation id, FriendlyByteBuf buffer) {
            //从buffer读取火焰数量
            int fireCount = buffer.readVarInt();
            //新建火焰list构造器
            ImmutableList.Builder<Block> fireBuilder = ImmutableList.builder();
            //循环获取火焰
            for (int i = 0; i < fireCount; i++) {
                fireBuilder.add(ForgeRegistries.BLOCKS.getValue(buffer.readResourceLocation()));
            }
            //从buffer中获取配方流体产物
            FluidStack output = buffer.readFluidStack();
            //从buffer中获取配方成分数量并创建集合
            NonNullList<Ingredient> input = NonNullList.withSize(buffer.readVarInt(), Ingredient.EMPTY);
            //从buffer中获取指定数量成分
            for (int i = 0; i < input.size(); i++) {
                input.set(i, Ingredient.fromNetwork(buffer));
            }
            return new FireFluidRecipe(id, fireBuilder.build(), input, output);
        }

        @Override
        public void toNetwork(FriendlyByteBuf buffer, FireFluidRecipe recipe) {
            //获取配方火焰
            ImmutableList<Block> fireBlock = recipe.fireBlock;
            //向buffer吸入火焰数量
            buffer.writeVarInt(fireBlock.size());
            //遍历写入火焰
            fireBlock.forEach((b) -> buffer.writeResourceLocation(b.getRegistryName()));
            //向buffer写入流体产物
            buffer.writeFluidStack(recipe.outputs);
            //获取配方成分
            NonNullList<Ingredient> inputs = recipe.inputs;
            //向buffer写入成分数量
            buffer.writeVarInt(inputs.size());
            //写入成分
            inputs.forEach((i) -> i.toNetwork(buffer));
        }
    }
}
